package com.demo.spring.lazy底层演示;

import java.lang.reflect.Field;

import org.springframework.beans.factory.annotation.AnnotatedGenericBeanDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.GenericApplicationContext;

public class Test {
	
	public static void main(String[] args) throws Exception {
		GenericApplicationContext context = new GenericApplicationContext();
		context.registerBeanDefinition("bean1", new AnnotatedGenericBeanDefinition(Bean1.class));
		context.registerBeanDefinition("bean2", new AnnotatedGenericBeanDefinition(Bean2.class));
		
		// ContextAnnotationAutowireCandidateResolver可以为lazy注解的属性返回代理
		ContextAnnotationAutowireCandidateResolver resolver = new ContextAnnotationAutowireCandidateResolver();
		resolver.setBeanFactory(context.getDefaultListableBeanFactory());
		Field bean2 = Bean1.class.getDeclaredField("bean2");
		DependencyDescriptor dd1 = new DependencyDescriptor(bean2, false);
		// @Lazy可以延迟生成bean
		Object proxy = resolver.getLazyResolutionProxyIfNecessary(dd1, "bean1");
		System.out.println(proxy);
		System.out.println(proxy.getClass());
	}
	
	static class Bean1 {
		@Autowired
		@Lazy
		private Bean2 bean2;
	}
	
	static class Bean2 {
		
	}

}
